package com.stylefeng.guns.modular.system.controller;

import com.stylefeng.guns.config.FileConfig;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.base.tips.Tip;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * #-  文件上传服务 -#
 *
 * @Auther: wangchuan
 * @Date: 2018/9/3 14:05
 */
@Slf4j
@RestController
public class FileController extends BaseController {

    @Autowired
    private FileConfig fileConfig;

    /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/fileUpload")
    @Permission({Const.ADMIN_NAME, Const.GE_ADMIN_NAME})
    public Tip upload(@RequestPart("file") MultipartFile picture, String dir) {
        String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename());
        Map data = new HashMap();
        try {
            String _dir = "";
            if(StringUtils.isNotBlank(dir)){
                _dir = dir.replaceAll("\\\\","/");
                if(_dir.startsWith("/"))
                    _dir = _dir.substring(1);
                if (!_dir.endsWith("/")) {
                    _dir += "/";
                }
            }
            String fileSavePath = fileConfig.getFileDiskPath()+fileConfig.getFileVirPath()+_dir;
            picture.transferTo(new File(fileSavePath + pictureName));
            log.info(fileSavePath + pictureName);
            data.put("relativeUrl",fileConfig.getFileVirPath()+_dir+pictureName);
        } catch (Exception e) {
            log.error("上传文件异常:",e);
            throw new GunsException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return new SuccessTip(data);
    }

}
